﻿using Dm;
using SqlSugar;
using SqlSugar.Extensions;
using System.Linq.Expressions;
using Zhao.Common.Helper;
using Zhao.IServer.Log;
using Zhao.IServer.Management_Arena;
using Zhao.Models.DTO;
using Zhao.Models.Entity;
using Zhao.Repository.Base;
using Zhao.Repository.UnitOfWork;
using static System.Net.Mime.MediaTypeNames;

namespace Zhao.Service.Management_Arena
{
    /// <summary>
    /// 球馆申请（入驻审核流程）
    ///</summary>
    public class VenueApplicationsServer : BaseService<VenueApplications>, IVenueApplicationsServer
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogsServer _logs;
        public VenueApplicationsServer(IBaseRepository<VenueApplications> baseDal, IUnitOfWork unitOfWork, ILogsServer logs) : base(baseDal, unitOfWork)
        {
            _unitOfWork = unitOfWork;
            _logs= logs;
        }

        /// <summary>
        /// 获取球馆申请入驻审核信息
        /// </summary>
        /// <param name="expressionable"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<PageModel<VenueApplicationDTO>> VenueApplicationsQuery(Expression<Func<VenueApplications, Admin, Users, Area, Area, Area, bool>> expressionable, int pageIndex, int pageSize)
        {
            //获取总条数
            RefAsync<int> totalCount = 0;

            var list = await _Client.Queryable<VenueApplications>()
                .LeftJoin<Admin>((a, b) => a.Review == b.Id)
                .LeftJoin<Users>((a, b, c) => a.CreatedByUserID == c.UserID)
                // 新增省市区表关联
                .LeftJoin<Area>((a, b, c, d) => a.Province == d.Id)// d 是 Province 表别名
                .LeftJoin<Area>((a, b, c, d, e) => a.City == e.Id)// e 是 City 表别名
                .LeftJoin<Area>((a, b, c, d, e, f) => a.Zone == f.Id)// f 是 District 表别名
                .WhereIF(expressionable != null, expressionable)
                .Select((a, b, c, d, e, f) => new VenueApplicationDTO
                {
                    ApplicationID = a.ApplicationID,
                    VenueName = a.VenueName,
                    Address =$"{d.Name}{e.Name}{f.Name}{a.Address}" ,
                    Images = a.Images,
                    ContactPhone = a.ContactPhone,
                    Description = a.Description,
                    Status = a.Status,
                    ApprovalOpinion = a.ApprovalOpinion,
                    CreatedAt = a.CreatedAt,
                    ReviewName = c.RealName,
                    CreatedByUser = b.UserName,
                    UpdatedAt = a.UpdatedAt,
                    VId=a.VenunId,
                    ManagerName=a.ManagerName,
                    Province=a.Province,
                    City=a.City,
                    District=a.Zone,
                    LicenseImage=a.License
                })
                .ToPageListAsync(pageIndex, pageSize, totalCount).ConfigureAwait(false);

            int totalPage = (Math.Ceiling(totalCount.ObjToDecimal() / pageSize.ObjToDecimal())).ObjToInt();

            return new PageModel<VenueApplicationDTO>() { count = totalCount, PageCount = totalPage, PageIndex = pageIndex, PageSize = pageSize, data = list, code = totalCount == 0 ? -1 : 0, msg = totalCount == 0 ? "未查询到任何数据" : "" };
        }



        /// <summary>
        /// 球馆入驻审核
        /// </summary>
        /// <param name="applications"></param>
        /// <param name="adminId"></param>
        /// <returns></returns>
        public async Task<ApiResult> ProcessReviewAsync(VenueApplications applications, int adminId)
        {
            var result = new ApiResult { Success = false };
            bool isApproved = applications.Status == 3; // 3-待开通账号，表示审核通过

            Guid guid =default;

            try
            {
                if (isApproved)
                {
                    await _Client.Ado.BeginTranAsync();
                    guid= Guid.NewGuid();
                }

                // 并发安全更新
                var updateSuccess = await _Client.Updateable<VenueApplications>()
                    .SetColumns(a => new VenueApplications
                    {
                        Status = applications.Status,
                        Review = adminId,
                        ApprovalOpinion = applications.ApprovalOpinion,
                        UpdatedAt = DateTime.Now,
                    })
                    .SetColumnsIF(isApproved,x=>x.VenunId== guid)
                    .Where(a => a.ApplicationID == applications.ApplicationID)
                    .ExecuteCommandAsync();

                if (updateSuccess == 0)
                {
                    if (isApproved) await _Client.Ado.RollbackTranAsync();
                    return new ApiResult { Message = "审核失败,请稍后在试", Success = false };
                }

                if (isApproved)
                {
                    //// 唯一性校验
                    //var exists = await _Client.Queryable<Venues>()
                    //    .Where(v => v.VenueName == applications.VenueName)
                    //    .AnyAsync();

                    //if (exists)
                    //{
                    //    await _Client.Ado.RollbackTranAsync();
                    //    return new ApiResult { Message = "场馆名称已存在" };
                    //}

                    var venue = new Venues
                    {
                        VenueID = guid,
                        VenueName = applications.VenueName,
                        Address = applications.Address,
                        Images = applications.Images,
                        Phone = applications.ContactPhone,
                        Description = applications.Description,
                        CreatedAt = DateTime.Now,
                        UpdatedAt = DateTime.Now,
                        IsDeleted =1,
                        ManagerName= applications.ManagerName,
                        License= applications.License,
                        Province = applications.Province,
                        City = applications.City,
                        Zone = applications.Zone
                    };

                    // 插入场馆数据
                    var insertSuccess = await _Client.Insertable(venue).ExecuteCommandAsync();
                    if (insertSuccess <= 0)
                    {
                        await _Client.Ado.RollbackTranAsync();
                        return new ApiResult { Message = "场馆创建失败", Success = false };
                    }

                    await _Client.Ado.CommitTranAsync();
                }

                await _logs.Info($"审核球馆入驻，球馆名称{applications.VenueName},审核人{adminId},成功");

                result.Message = "操作成功";
                result.Success= true;
                return result;
            }
            catch (Exception ex)
            {
               await _Client.Ado.RollbackTranAsync();

                await _logs.Info($"审核球馆入驻，球馆名称{applications.VenueName},审核人{adminId}，失败原因:{ex.Message}");

                return new ApiResult { Message = $"审核失败，请稍后在试",Success=false};
            }
        }

        #region 小程序
        /// <summary>
        /// 小程序端添加球馆申请
        /// </summary>
        /// <param name="application"></param>
        /// <returns></returns>
        public async Task<ApiResult> AddVenueApplicationAsync(VenueApplications application)
        {
            var result = new ApiResult { Success = false };
            try
            {
                application.Status = 1; // 默认待审核
                application.CreatedAt = DateTime.Now;
                application.UpdatedAt = DateTime.Now;
                var insert = await _Client.Insertable(application).ExecuteCommandAsync();
                if (insert > 0)
                {
                    result.Success = true;
                    result.Message = "提交成功，等待审核";
                }
                else
                {
                    result.Message = "提交失败，请稍后再试";
                }
            }
            catch (Exception ex)
            {
                result.Message = $"提交失败：{ex.Message}";
            }
            return result;
        }

        /// <summary>
        /// 查询用户是否已提交过球馆入驻申请
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>申请状态和数据</returns>
        public async Task<ApiResult<VenueApplicationDTO>> CheckUserApplicationAsync(int userId)
        {
            var result = new ApiResult<VenueApplicationDTO> { Success = false };

            try
            {
                // 查询用户最近一次的申请记录
                var application = await _Client.Queryable<VenueApplications>()
                    .Where(x => x.CreatedByUserID == userId)
                    .OrderByDescending(x => x.CreatedAt)
                    .FirstAsync();

                if (application == null)
                {
                    // 用户未提交过申请
                    result.StatusCode = 404; // 使用特定状态码表示未找到申请
                    result.Message = "未找到申请记录";
                    return result;
                }

                // 查询关联数据，构建完整的DTO
                var applicationDto = await _Client.Queryable<VenueApplications>()
                    .LeftJoin<Admin>((a, b) => a.Review == b.Id)
                    .LeftJoin<Users>((a, b, c) => a.CreatedByUserID == c.UserID)
                    .Where((a, b, c) => a.ApplicationID == application.ApplicationID)
                    .Select((a, b, c) => new VenueApplicationDTO
                    {
                        ApplicationID = a.ApplicationID,
                        VenueName = a.VenueName,
                        Address = a.Address,
                        Images = a.Images,
                        ContactPhone = a.ContactPhone,
                        Description = a.Description,
                        Status = a.Status,
                        ApprovalOpinion = a.ApprovalOpinion,
                        CreatedAt = a.CreatedAt,
                        ReviewName = c.RealName,
                        CreatedByUser = b.UserName,
                        UpdatedAt = a.UpdatedAt,
                        VId = a.VenunId,
                        ManagerName = a.ManagerName,
                        Province = a.Province,
                        City = a.City,
                        District = a.Zone,
                        LicenseImage = a.License
                    })
                    .FirstAsync();

                if (applicationDto != null)
                {
                    result.Success = true;
                    result.Data = applicationDto;
                    result.Message = "获取申请记录成功";
                    
                    // 根据申请状态设置不同的状态码
                    switch (applicationDto.Status)
                    {
                        case 1: // 待审核
                            result.StatusCode = 201;
                            break;
                        case 3: // 已通过
                            result.StatusCode = 200;
                            break;
                        case 5: // 已拒绝
                            result.StatusCode = 202;
                            break;
                        default:
                            result.StatusCode = 0;
                            break;
                    }
                }
                else
                {
                    result.StatusCode = 500;
                    result.Message = "获取申请详情失败";
                }
            }
            catch (Exception ex)
            {
                result.StatusCode = 500;
                result.Message = $"查询失败：{ex.Message}";
            }

            return result;
        }
        #endregion

        /// <summary>
        /// 查询用户申请状态
        /// </summary>
        /// <param name="userId">用户ID</param>
        /// <returns>申请状态，如果没有申请则返回0</returns>
        public async Task<ApiResult<short>> GetUserApplicationStatusAsync(int userId)
        {
            var result = new ApiResult<short> { Success = true, Data = 0 };

            try
            {
                // 查询用户最近一次的申请记录
                var application = await _Client.Queryable<VenueApplications>()
                    .Where(x => x.CreatedByUserID == userId)
                    .OrderByDescending(x => x.CreatedAt)
                    .Select(x => new { x.Status })
                    .FirstAsync();

                if (application != null)
                {
                    result.Data = application.Status;
                }
                
                result.Message = "获取状态成功";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = $"查询失败：{ex.Message}";
            }

            return result;
        }

        /// <summary>
        /// 重新提交球馆入驻申请
        /// </summary>
        /// <param name="applicationId">申请ID</param>
        /// <param name="application">更新后的申请信息</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> ReapplyVenueApplicationAsync(int applicationId, VenueApplications application)
        {
            var result = new ApiResult { Success = false };
            try
            {
                // 查询原申请记录
                var existingApplication = await _Client.Queryable<VenueApplications>()
                    .Where(x => x.ApplicationID == applicationId)
                    .FirstAsync();

                if (existingApplication == null)
                {
                    result.Message = "申请记录不存在";
                    return result;
                }

                // 检查申请状态是否为已拒绝(7)
                if (existingApplication.Status != 7)
                {
                    result.Message = "只有被驳回的申请才能重新提交";
                    return result;
                }

                // 更新申请信息
                var updateSuccess = await _Client.Updateable<VenueApplications>()
                    .SetColumns(a => new VenueApplications
                    {
                        VenueName = application.VenueName,
                        Address = application.Address,
                        Images = application.Images,
                        ContactPhone = application.ContactPhone,
                        Description = application.Description,
                        ManagerName = application.ManagerName,
                        Province = application.Province,
                        City = application.City,
                        Zone = application.Zone,
                        License = application.License,
                        Status = 9, // 重新审核状态
                        UpdatedAt = DateTime.Now
                    })
                    .Where(a => a.ApplicationID == applicationId)
                    .ExecuteCommandAsync();

                if (updateSuccess > 0)
                {
                    result.Success = true;
                    result.Message = "重新申请提交成功，等待审核";
                }
                else
                {
                    result.Message = "重新申请提交失败，请稍后再试";
                }
            }
            catch (Exception ex)
            {
                result.Message = $"重新申请失败：{ex.Message}";
            }
            return result;
        }

        /// <summary>
        /// 更新申请状态为已完成
        /// </summary>
        /// <param name="venueId">球馆ID</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult> UpdateApplicationStatusToCompletedAsync(Guid venueId)
        {
            var result = new ApiResult { Success = false };
            
            try
            {
                // 查询与该球馆ID关联的申请记录
                var application = await _Client.Queryable<VenueApplications>()
                    .Where(a => a.VenunId == venueId)
                    .OrderByDescending(a => a.UpdatedAt)
                    .FirstAsync();
                
                if (application == null)
                {
                    result.Message = "未找到关联的申请记录";
                    return result;
                }
                
                // 检查申请状态是否为待开通账号(3)
                if (application.Status != 3)
                {
                    result.Message = "只有待开通账号的申请才能标记为已完成";
                    return result;
                }
                
                // 更新申请状态为已完成(5)
                var updateSuccess = await _Client.Updateable<VenueApplications>()
                    .SetColumns(a => new VenueApplications
                    {
                        Status = 5, // 已完成
                        UpdatedAt = DateTime.Now
                    })
                    .Where(a => a.ApplicationID == application.ApplicationID)
                    .ExecuteCommandAsync();
                
                if (updateSuccess > 0)
                {
                    result.Success = true;
                    result.Message = "申请状态已更新为已完成";
                }
                else
                {
                    result.Message = "申请状态更新失败";
                }
            }
            catch (Exception ex)
            {
                result.Message = $"更新申请状态失败：{ex.Message}";
            }
            
            return result;
        }
    }
}
